﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LinkCard.AdminCP.Common;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using LinkCard.Model;
using LinkCard.Dao;

namespace LinkCard.ShopCP.Reports
{
    public partial class report_detail : System.Web.UI.Page
    {
        public string sFromDate = "";
        public string sToDate = "";
        public DateTime dFromDate = new DateTime(1900, 1, 1);
        public DateTime dToDate = new DateTime(2099, 1, 1);

        private int _totalRecords;

        private int nPageSize = 20;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USER"] == null)
            {
                Response.Redirect("/message_box.aspx?msg=5");
            }

            if (!Page.IsPostBack)
            {
                if (Request.QueryString["FromDate"] != null) { sFromDate = Request.QueryString["FromDate"].Trim(); }
                if (Request.QueryString["ToDate"] != null) { sToDate = Request.QueryString["ToDate"].Trim(); }


                DataBindPaging();
            }

        }

        private void DataBindPaging()
        {

            try
            {
                var db = new TopLinkEntities();

                Int64 nSupplierID = getSupplierID();
                int curpage = 0;
                int skip = 0;

                if (Request.QueryString["page"] != null)
                {
                    if (Request.QueryString["page"].ToString() != "1")
                    {
                        curpage = Convert.ToInt32(Request.QueryString["page"]);
                        skip = (curpage-1) * nPageSize;
                    }
                    else
                    {
                        curpage = 1;
                        skip = 0;
                    }
                }
                else
                {
                    curpage = 1;
                    skip = 0;
                }

                System.Globalization.DateTimeFormatInfo dateInfo = new System.Globalization.DateTimeFormatInfo();
                dateInfo.ShortDatePattern = "dd/MM/yyyy";

                if (sFromDate != "")
                {
                    sFromDate += " 00:00:00";
                    dFromDate = Convert.ToDateTime(sFromDate, dateInfo);

                }
                if (sToDate != "")
                {
                    sToDate += " 23:59:59";
                    dToDate = Convert.ToDateTime(sToDate, dateInfo);
                }

                var _paylog = (from payment in db.PayLog
                               let dt = payment.PayDate
                               where (payment.SupplierID == nSupplierID
                                     && payment.PayDate >= dFromDate
                                     && payment.PayDate <= dToDate)
                               group payment by new { y = dt.Value.Year, m = dt.Value.Month, d = dt.Value.Day } into p
                               select new
                               {
                                   PayYear = p.Key.y,
                                   PayMonth = p.Key.m,
                                   PayDay = p.Key.d,
                                   PayAmountSum = p.Sum(s => s.PayAmount),
                                   PayCount = p.Count()
                               }).OrderBy(t => new { t.PayYear, t.PayMonth, t.PayDay}).Skip(skip).Take(nPageSize);

                //var _paylog = db.PayLog.Where(t => t.SupplierID == nSupplierID
                //                                && t.PayDate >= dFromDate
                //                                && t.PayDate <= dToDate).GroupBy(t => t.PayDate.Value.Date);
                _totalRecords = (from payment in db.PayLog
                                 let dt = payment.PayDate
                                 where (payment.SupplierID == nSupplierID
                                       && payment.PayDate >= dFromDate
                                       && payment.PayDate <= dToDate)
                                 group payment by new { y = dt.Value.Year, m = dt.Value.Month, d = dt.Value.Day } into p
                                 select new
                                 {
                                     PayYear = p.Key.y,
                                     PayMonth = p.Key.m,
                                     PayDay = p.Key.d,
                                     PayAmountSum = p.Sum(s => s.PayAmount),
                                     PayCount = p.Count()
                                 }).OrderBy(t => new { t.PayYear, t.PayMonth, t.PayDay }).ToList().Count;

                var paylog = _paylog.ToList();

                if (paylog.Count > 0)
                {
                    int nPageCount;

                    

                    if (_totalRecords % nPageSize == 0)
                    {
                        nPageCount = _totalRecords / nPageSize;
                    }
                    else
                    {
                        nPageCount = Convert.ToInt32(_totalRecords / nPageSize) + 1;
                    }

                    if (nPageCount < 2) divPager.Visible = false;

                    PagerShow.Text = hash1way.ShowPageNavigation(curpage, nPageCount);

                    msgList.DataSource = paylog;

                    msgList.DataBind();
                    msgNoData.Visible = false;
                }
                else
                {
                    msgList.DataSource = null;
                    msgList.DataSourceID = null;
                    msgList.DataBind();
                    msgNoData.Visible = true;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

        protected void msgList_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {

            Response.Redirect("export_by_date.aspx?FromDate=" + sFromDate + "&ToDate=" + sToDate + "");
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

            sFromDate = FromDate.Value.Trim();
            sToDate = ToDate.Value.Trim();
            DataBindPaging();

        }
        protected Int64 getSupplierID()
        {
            try
            {

                if (Convert.ToInt32(Session["SHOPADMIN"]) == 1) // quanr ly cua hang
                {
                    return ConvertUtility.ToInt64(Session["USER"]);
                }
                else if (Convert.ToInt32(Session["SHOPADMIN"]) == 0)
                {
                    DataTable dt = LinkCard.AdminCP.Common.DataHelper.SelectTable("SELECT SupplierID FROM [ShopStaff] WHERE Username ='" + Session["USER"].ToString() + "'", false);
                    if (dt.Rows.Count > 0)
                    {
                        return ConvertUtility.ToInt64(dt.Rows[0]["SupplierID"]);
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    return 0;
                }
            }
            catch
            {
                return 0;
            }
        }


    }
}